import httplib
import base64
import logging
import string

from config import config

logger = logging.getLogger()

class TrackEyeClient(object):
    def __init__(self):
        pass

    def get_screenshot(self):
        pass

    def _connection(self, url, method='GET', data=None):
        host = config.get('api', 'host')
        auth = config.get('api', 'auth')
        connection = httplib.HTTPConnection(host)
        auth = 'Basic ' + string.strip(base64.encodestring(auth))
        connection.putrequest(method, url)
        connection.putheader('Authorization', auth)

        if data is not None:
            connection.putheader('Content-length', len(data))
            connection.putheader('Content-type', 'application/json')

        connection.endheaders()

        if data is not None:
            connection.send(data)

        return connection

    def _get_response(self, connection, attempts=3):
        if not connection:
            return
        response = None
        while attempts:
            try:
                response = connection.getresponse()
            except (socket.error,
                    httplib.ImproperConnectionState,
                    httplib.BadStatusLine) as exc:
                attempts -= 1
                logger.exception("Caught %s while calling Trackeye API. %i attempts left..." % (type(exc), attempts))
                time.sleep(1)
            else:
                break
        return response

    def get_test(self):
        url = '/api/log/'
        conn = self._connection(url, 'GET')
        resp = self._get_response(conn)
        print resp.read()


